﻿package com.sgcc.nfc.lock.presentation.rooms

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Room
import com.sgcc.nfc.lock.domain.model.RoleType
import com.sgcc.nfc.lock.domain.usecase.GetProfileUseCase
import com.sgcc.nfc.lock.domain.usecase.GetRoomsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@HiltViewModel
class RoomsViewModel @Inject constructor(
    private val getRoomsUseCase: GetRoomsUseCase,
    private val getProfileUseCase: GetProfileUseCase
) : ViewModel() {

    private val _rooms = MutableLiveData<List<Room>>(emptyList())
    val rooms: LiveData<List<Room>> = _rooms

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private var searchJob: Job? = null
    private var keywordCache: String? = null
    private var regionFilterId: Long? = null
    private var profileLoaded = false

    init {
        loadRooms()
    }

    fun loadRooms(keyword: String? = null) {
        keywordCache = keyword
        _isLoading.value = true
        viewModelScope.launch {
            ensureRegionFilter()
            when (val result = getRoomsUseCase(page = 1, pageSize = 50, regionId = regionFilterId, keyword = keyword)) {
                is NetworkResult.Success -> {
                    _rooms.value = result.data.data
                    _error.value = null
                }
                is NetworkResult.Error -> _error.value = result.message
                NetworkResult.Loading -> _isLoading.value = true
            }
            _isLoading.value = false
        }
    }

    fun search(keyword: String) {
        searchJob?.cancel()
        searchJob = viewModelScope.launch {
            delay(300)
            loadRooms(keyword.takeIf { it.isNotBlank() })
        }
    }

    fun currentKeyword(): String? = keywordCache

    private suspend fun ensureRegionFilter() {
        if (profileLoaded) return
        when (val result = getProfileUseCase()) {
            is NetworkResult.Success -> {
                val user = result.data
                val role = RoleType.fromValue(user.roleType)
                regionFilterId = if (role == null || role == RoleType.SUPER_ADMIN) null else user.regionId
            }
            is NetworkResult.Error -> _error.postValue(result.message)
            NetworkResult.Loading -> Unit
        }
        profileLoaded = true
    }
}
